package com.atguigu.gmall.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;

@Slf4j
public class JsonUtils {

    static ObjectMapper objectMapper = new ObjectMapper();

    public static String parseObjectToJsonStr(Object obj){
        String json = null;
        try {
            json = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("json转换异常：被转对象：{}, 异常信息：{}",obj,e);
        }
        return json;
    }

    public static<T> T parseJsonStrToObject(String json,
                                                TypeReference<T> reference) {

        T t = null;
        try {
            t = objectMapper.readValue(json, reference);
        } catch (JsonProcessingException e) {
            log.error("json转换异常：被转json：{}, 异常信息：{}",json,e);
        }
        return t;
    }

    public static<T> T converMessageToObject(Message message, TypeReference<T> reference) {
        String json = new String(message.getBody());
        return parseJsonStrToObject(json,reference);

    }
}
